package com.mrd.gtimpframe.service.impl;

import com.mrd.gtimpframe.entity.Attachment;
import com.mrd.gtimpframe.repository.AttachmentMapper;
import com.mrd.gtimpframe.service.AttachmentService;
import com.mrd.gtimpframe.service.CompanyAttachmentService;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

@Service
public class AttachmentServiceImpl implements AttachmentService {
    @Resource
    private AttachmentMapper attachmentMapper;
    @Resource
    private CompanyAttachmentService companyAttachmentService;
    @Value("${file.path}")
    private String fileDir;

    @Override
    @Transactional
    public int deleteByPrimaryKey(String id) {
        return attachmentMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public int insert(Attachment record) {
        return attachmentMapper.insert(record);
    }

    @Override
    @Transactional
    public int insertSelective(Attachment record) {
        return attachmentMapper.insertSelective(record);
    }

    @Override
    public Attachment selectByPrimaryKey(String id) {
        return attachmentMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public int updateByPrimaryKeySelective(Attachment record) {
        return attachmentMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    @Transactional
    public int updateByPrimaryKey(Attachment record) {
        return attachmentMapper.updateByPrimaryKey(record);
    }

    /**
     * 根据公司关系获取公司附件列表
     */
    @Override
    public List<Attachment> getAttachmentList(String agentRefId) {
        return attachmentMapper.selectByAgentRef(agentRefId);
    }

    /**
     * 删除附件（仅删除数据库信息）
     */
    @Override
    @Transactional
    public void deleteattAchment(String id) {
        companyAttachmentService.deleteByPrimaryKey(id);
        this.deleteByPrimaryKey(id);
    }

    /**
     * 下载附件
     */
    @Override
    public void downloadAttachment(HttpServletRequest request, HttpServletResponse response, String id) {
        Attachment attachment = this.selectByPrimaryKey(id);
        if (attachment == null) {
            return;
        }
        String filePath = String.format("%s\\%s", fileDir, attachment.getPath());
        this.download(request, response, filePath, attachment.getName());
    }

    /**
     * 设置让浏览器弹出下载对话框的Header. 根据浏览器的不同设置不同的编码格式 防止中文乱码
     *
     * @param fileName 下载后的文件名.
     */
    private void download(HttpServletRequest request, HttpServletResponse response, String downloadFilePath, String fileName) {
        File downFiles = new File(downloadFilePath);
        if (!downFiles.exists()) {
            return;
        }
        if (!fileName.contains(".") && downloadFilePath.contains(".")) {
            fileName += downloadFilePath.substring(downloadFilePath.lastIndexOf("."));
        }
        try (InputStream fis = new FileInputStream(downFiles); BufferedInputStream bis = new BufferedInputStream(fis); OutputStream fos = response.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            // 中文文件名支持
            String encodedFileName;
            String agent = request.getHeader("USER-AGENT");
            if (agent != null && agent.contains("MSIE")) {// IE
                encodedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else if (agent != null && agent.contains("Mozilla")) {
                encodedFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } else {
                encodedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
            response.setHeader("Content-Length", "" + downFiles.length());
            int byteRead;
            byte[] buffer = new byte[2048];
            while ((byteRead = bis.read(buffer, 0, 2048)) != -1) {
                bos.write(buffer, 0, byteRead);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
